﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using giaoxuhaison.Models;
using giaoxuhaison.Common;

namespace giaoxuhaison.Controllers
{
    public class SearchController : Controller
    {
        //
        // GET: /Search/
        private gxhaisonEntities conn = new gxhaisonEntities();

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Search()
        {
            return PartialView();
        }

        public ActionResult SearchResult(string search, int currentPage = 1)
        {
            
            if (!string.IsNullOrEmpty(search))
            {
                Common.Common.strSearch = search;
            }

            var model = SearchNews(Common.Common.strSearch, currentPage);
            return View(model);
        }

        public ActionResult _MenuLeft()
        {
            /*get data list group*/
            /*var lstGroup = conn.GroupAlls.Where(t => t.GroupType == 2 && t.Locked == false).OrderBy(t => t.GroupID).ToList();*/

            ViewData["lstGroup"] = GetListGroup();
            ViewData["lstCategoryAll"] = GetCategoryAll();
            return PartialView();
        }

        /*Dinh nghia cac ham lay du lieu*/
        
        private List<GroupAll> GetListGroup()
        {
            var lstGroup = conn.GroupAlls.Where(t => t.GroupType == 2 && t.Locked == false).OrderBy(t => t.GroupID).ToList();
            return lstGroup;
        }

        private List<vw_CategoriesAll> GetCategoryAll()
        {
            var lstItem = conn.vw_CategoriesAll.Where(t => t.Locked == false).OrderBy(t => t.GroupID).OrderByDescending(t => t.CreationDate).ToList();
            return lstItem;
        }
        /**/
        private ResultList SearchNews(string search, int currentPage = 1)
        {
            var skipNumber = (currentPage - 1) * 6;
            var resultList = new ResultList();
            var repNewsAll = conn.vw_Search.Where(t => t.Locked == false && (t.Contents.Contains(search) || t.Subject.Contains(search))).OrderByDescending(t => t.CreationDate).AsQueryable();

            resultList.CurrentPage = currentPage;
            resultList.TotalRecords = repNewsAll.Count();
            resultList.EntityList = repNewsAll.Skip(skipNumber).Take(6).ToList().Select(t => t as ModelBase).ToList();

            return resultList;

        }
    }
}
